package com.ruoyi.project.websitenewstrends.controller;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.websitefilemanage.domain.WebsiteFileManage;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.websitenewstrends.domain.WebsiteNewsTrends;
import com.ruoyi.project.websitenewstrends.service.IWebsiteNewsTrendsService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * newstrendsController     首页新闻动态内容
 * 
 * @author lvyongwei
 * @date 2021-04-20
 */
@Controller
@RequestMapping("/website/websitenewstrends")
public class WebsiteNewsTrendsController extends BaseController
{
    private String prefix = "system/websitenewstrends";

    @Autowired
    private IWebsiteNewsTrendsService websiteNewsTrendsService;

    @RequiresPermissions("website:websitenewstrends:view")
    @GetMapping()
    public String websitenewstrends()
    {
        return prefix + "/websitenewstrends";
    }

    /**
     * 查询newstrends列表
     */
    @RequiresPermissions("website:websitenewstrends:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WebsiteNewsTrends websiteNewsTrends)
    {
        startPage();
        List<WebsiteNewsTrends> list = websiteNewsTrendsService.selectWebsiteNewsTrendsList(websiteNewsTrends);
        return getDataTable(list);
    }

    /**
     * 导出newstrends列表
     */
    @RequiresPermissions("website:websitenewstrends:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WebsiteNewsTrends websiteNewsTrends)
    {
        List<WebsiteNewsTrends> list = websiteNewsTrendsService.selectWebsiteNewsTrendsList(websiteNewsTrends);
        ExcelUtil<WebsiteNewsTrends> util = new ExcelUtil<WebsiteNewsTrends>(WebsiteNewsTrends.class);
        return util.exportExcel(list, "websitenewstrends");
    }

    /**
     * 新增newstrends
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存newstrends
     */
    @RequiresPermissions("website:websitenewstrends:add")
    @Log(title = "newstrends", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WebsiteNewsTrends websiteNewsTrends, MultipartFile[] files)
    {
        //定义存储文件路径
        String accessorys = "";
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        //附件上传并赋值
        if(StringUtils.isEmpty(files) || files.length == 0){
            websiteNewsTrends.setNewsPhoto(null);
            websiteNewsTrends.setAccessorys(null);
        }else{
            try{
                //如果文件数组只有一个文件
                if(files.length == 1){
                    //判断这一个文件是否是图片类型
                    String fileName = files[0].getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
                    if(".jpg".equalsIgnoreCase(suffix) || ".png".equalsIgnoreCase(suffix) || ".gif".equalsIgnoreCase(suffix)){
                        String name = FileUploadUtils.upload(filePath, files[0]);
                        websiteNewsTrends.setNewsPhoto(name);
                    }else{
                        String name = FileUploadUtils.upload(filePath, files[0]);
                        accessorys += files[0].getOriginalFilename() + ":" +name + ";";
                        websiteNewsTrends.setAccessorys(accessorys);
                    }
                }else{
                    //判断第一个文件是否是图片类型，附件不允许上传图片类型，因此第一个若不是图片类型则全为附件
                    String fileName = files[0].getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
                    if(".jpg".equalsIgnoreCase(suffix) || ".png".equalsIgnoreCase(suffix) || ".gif".equalsIgnoreCase(suffix)){
                        //若文件数组不止一个文件,即封面和文件都存在
                        String name = FileUploadUtils.upload(filePath, files[0]);
                        websiteNewsTrends.setNewsPhoto(name);
                        for(int i=1;i<files.length;i++){
                            // 上传并返回新文件名称
                            String fileName1 = FileUploadUtils.upload(filePath, files[i]);
                            accessorys += files[i].getOriginalFilename() + ":" +fileName1 + ";";
                        }
                        websiteNewsTrends.setAccessorys(accessorys);
                    }else{
                        for(int i=0;i<files.length;i++){
                            // 上传并返回新文件名称
                            String fileName1 = FileUploadUtils.upload(filePath, files[i]);
                            accessorys += files[i].getOriginalFilename() + ":" +fileName1 + ";";
                        }
                        websiteNewsTrends.setAccessorys(accessorys);
                        websiteNewsTrends.setNewsPhoto(null);
                    }
                }
            }catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
        }
        /**
         * 字段赋值
         */
        websiteNewsTrends.setIfShow(0);
        System.err.println(websiteNewsTrends);
        return toAjax(websiteNewsTrendsService.insertWebsiteNewsTrends(websiteNewsTrends));
    }

    /**
     * 修改newstrends
     */
    @GetMapping("/edit/{newsId}")
    public String edit(@PathVariable("newsId") Long newsId, ModelMap mmap)
    {
        WebsiteNewsTrends websiteNewsTrends = websiteNewsTrendsService.selectWebsiteNewsTrendsById(newsId);
        mmap.put("websiteNewsTrends", websiteNewsTrends);
        return prefix + "/edit";
    }

    /**
     * 修改保存newstrends
     */
    @RequiresPermissions("website:websitenewstrends:edit")
    @Log(title = "newstrends", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WebsiteNewsTrends websiteNewsTrends, MultipartFile[] files)
    {
        //定义存储文件路径
        String accessorys = "";
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        //附件上传并赋值
        if(StringUtils.isEmpty(files) || files.length == 0){
            websiteNewsTrends.setNewsPhoto(null);
            websiteNewsTrends.setAccessorys(null);
        }else{
            try{
                //如果文件数组只有一个文件
                if(files.length == 1){
                    //判断这一个文件是否是图片类型
                    String fileName = files[0].getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
                    if(".jpg".equalsIgnoreCase(suffix) || ".png".equalsIgnoreCase(suffix) || ".gif".equalsIgnoreCase(suffix)){
                        String name = FileUploadUtils.upload(filePath, files[0]);
                        websiteNewsTrends.setNewsPhoto(name);
                    }else{
                        String name = FileUploadUtils.upload(filePath, files[0]);
                        accessorys += files[0].getOriginalFilename() + ":" +name + ";";
                        websiteNewsTrends.setAccessorys(accessorys);
                    }
                }else{
                    //判断第一个文件是否是图片类型，附件不允许上传图片类型，因此第一个若不是图片类型则全为附件
                    String fileName = files[0].getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
                    if(".jpg".equalsIgnoreCase(suffix) || ".png".equalsIgnoreCase(suffix) || ".gif".equalsIgnoreCase(suffix)){
                        //若文件数组不止一个文件,即封面和文件都存在
                        String name = FileUploadUtils.upload(filePath, files[0]);
                        websiteNewsTrends.setNewsPhoto(name);
                        for(int i=1;i<files.length;i++){
                            // 上传并返回新文件名称
                            String fileName1 = FileUploadUtils.upload(filePath, files[i]);
                            accessorys += files[i].getOriginalFilename() + ":" +fileName1 + ";";
                        }
                        websiteNewsTrends.setAccessorys(accessorys);
                    }else{
                        for(int i=0;i<files.length;i++){
                            // 上传并返回新文件名称
                            String fileName1 = FileUploadUtils.upload(filePath, files[i]);
                            accessorys += files[i].getOriginalFilename() + ":" +fileName1 + ";";
                        }
                        websiteNewsTrends.setAccessorys(accessorys);
                        websiteNewsTrends.setNewsPhoto(null);
                    }
                }
            }catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
        }
        return toAjax(websiteNewsTrendsService.updateWebsiteNewsTrends(websiteNewsTrends));
    }

    /**
     * 修改保存newstrends
     */
    @RequiresPermissions("website:websitenewstrends:edit")
    @Log(title = "newstrends", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus")
    @ResponseBody
    public AjaxResult editStatus(WebsiteNewsTrends websiteNewsTrends)
    {
        /**
         * 判断无图片时，不能设为轮播
         */
        if(websiteNewsTrends.getIfShow().equals(1)){
            WebsiteNewsTrends websiteNewsTrends1 = websiteNewsTrendsService.selectWebsiteNewsTrendsById(websiteNewsTrends.getNewsId());
            if(websiteNewsTrends1.getNewsPhoto() == null){
                return AjaxResult.error("该新闻没有图片，不能设置为轮播");
            }
        }
        return toAjax(websiteNewsTrendsService.updateWebsiteNewsTrends(websiteNewsTrends));
    }

    /**
     * 删除newstrends
     */
    @RequiresPermissions("website:websitenewstrends:remove")
    @Log(title = "newstrends", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(websiteNewsTrendsService.deleteWebsiteNewsTrendsByIds(ids));
    }


    /**
     * 查看新闻详情
     */
    @GetMapping("/look/{newsId}")
    public String look(@PathVariable("newsId") Long newsId, ModelMap mmap)
    {
        WebsiteNewsTrends websiteNewsTrends = websiteNewsTrendsService.selectWebsiteNewsTrendsById(newsId);
        mmap.put("websiteNewsTrends", websiteNewsTrends);
        return prefix + "/look";
    }

    /**
     * 返回给前端展示新闻动态
     * @param data
     * @return
     */
    @PostMapping("/getAllNewsTrends")
    @ResponseBody
    @CrossOrigin
    public AjaxResult getAllNewsTrends(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        if(StringUtils.isEmpty(pageNum) || pageNum == null){
            pageNum = 1;
        }
        if(StringUtils.isEmpty(pageSize) || pageSize == null){
            pageSize = 10;
        }
        try{
            /**
             * 获取轮播的新闻信息
             */
            List<WebsiteNewsTrends> websiteNewsTrends = websiteNewsTrendsService.getPlayNewsTrends();
            /**
             * 分页获取新闻动态
             */
            PageHelper.startPage(pageNum,pageSize);
            List<WebsiteNewsTrends> websiteNewsTrendsList = websiteNewsTrendsService.getAllNewsTrends();
            PageInfo<WebsiteNewsTrends> pageInfo = new PageInfo<WebsiteNewsTrends>(websiteNewsTrendsList);
            /**
             * 配置返回内容
             */
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("websiteNewsTrends",websiteNewsTrends);
            ajaxResult.put("websiteNewsTrendsList",pageInfo);
            ajaxResult.put("code",0);
            ajaxResult.put("msg","获取内容成功");
            return ajaxResult;
        }catch (Exception e){
            return AjaxResult.error("获取内容失败");
        }
    }


    /**
     * 根据新闻id获取新闻内容
     * @return
     */
    @PostMapping("/getNewsTrendsById")
    @ResponseBody
    @CrossOrigin
    public AjaxResult getNewsTrendsById(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Long newsId = jsonObject.getLong("newsId");
        WebsiteNewsTrends websiteNewsTrends = websiteNewsTrendsService.selectWebsiteNewsTrendsById(newsId);
        return AjaxResult.success("获取数据成功",websiteNewsTrends);
    }
}
